<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace service;


use PclZip;

/**
 *
 * Class ZipService
 * @author SuperX <xieshouchao@cuci.cc>
 * @package service
 */
class ZipService
{

    protected function compress()
    {
        $zipFile = new \PhpZip\ZipFile();
        try {
            $zipFile
                ->openFile()// open archive from file
                ->extractTo('source'); // extract files to the specified directory
//                ->deleteFromRegex('~^\.~') // delete all hidden (Unix) files
//                ->addFromString('dir/file.txt', 'Test file') // add a new entry from the string
//                ->setPassword('password') // set password for all entries
//                ->outputAsAttachment('小吃.zip'); // output to the browser without saving to a file

            // open archive, extract, add files, set password and output to browser.
            // 压缩文件
//                $file = env('root_path') . substr($fileData, strpos($fileData, 'public/'));
//                $zipFile
//                    ->addFromString('111.txt', 'hello word') // add an entry from the string
//                    ->addFile("./source", "data/tofile") // add an entry from the file
//                    ->addDir('source') // add files from the directory
//                    ->saveAsFile('demo.zip') // save the archive to a file
//                    ->close(); // close archive
        } catch (\PhpZip\Exception\ZipException $e) {
            // handle exception
        } finally {
            $zipFile->close();
        }
    }


    /**
     * 解压ZIP文件
     * @param $file zip压缩文件
     * @param $dir 解压目录
     * @throws \Exception
     */
    public static function unzip($file, $dir)
    {
        $zipFile = new \PhpZip\ZipFile();
        try {
            $zipFile->openFile($file)->extractTo($dir);
        } catch (\PhpZip\Exception\ZipException $e) {
            throw new \Exception($e->getMessage());
        } finally {
            $zipFile->close();
        }
    }


}
